package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.order.order.entity.dos.PrizeGoods;
import cn.lili.modules.order.order.entity.dos.PrizeOrder;
import cn.lili.modules.order.order.entity.dto.PrizeGoodsDTO;
import cn.lili.modules.order.order.entity.vo.RaffleGoodsVO;
import cn.lili.modules.order.order.mapper.AuditOrderMapper;
import cn.lili.modules.order.order.mapper.PrizeGoodsMapper;
import cn.lili.modules.order.order.service.OrderStatisticsService;
import cn.lili.modules.order.order.service.PrizeGoodsService;
import cn.lili.modules.order.order.service.PrizeOrderService;
import cn.lili.modules.system.client.DictionaryClient;
import cn.lili.modules.system.constants.DictConstant;
import cn.lili.modules.system.entity.dos.Dictionary;
import com.api.PayApi;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pojos.UserRes;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author asus
 * @description 针对表【li_prize_goods】的数据库操作Service实现
 * @createDate 2024-01-18 13:45:59
 */
@Service
@AllArgsConstructor(onConstructor_= @Lazy)
public class PrizeGoodsServiceImpl extends ServiceImpl<PrizeGoodsMapper, PrizeGoods> implements PrizeGoodsService {

    private PayApi payApi;

    private DictionaryClient dictionaryClient;

    private PrizeOrderService prizeOrderService;

    /**
     * 抽奖商品
     */
    @Override
    public ResultMessage<Object> raffleGoods() {
        //给用户展示抽奖的商品
        LambdaQueryWrapper<PrizeGoods> queryWrapper = this.createWrapper();
        List<PrizeGoods> prizeGoodsList = super.list(queryWrapper);
        if (CollectionUtil.isEmpty(prizeGoodsList)) {
            return ResultUtil.data(new ArrayList<>());
        }
        //实际参与抽奖的商品
        List<PrizeGoods> goodsList = prizeOrderService.prizeGoodsList();
        if (CollectionUtil.isEmpty(goodsList)) {
            throw new ServiceException("当前无商品参与抽奖,请联系管理员配置");
        }
        //获取单次抽奖，所需的f分
        Dictionary dictionary = dictionaryClient.getDict(Dictionary.builder().code(DictConstant.PRIZE_PRICE_NO).value(DictConstant.PRIZE_PRICE_01 + "").build());
        if (dictionary == null || StringUtils.isEmpty(dictionary.getId())) {
            throw new ServiceException("未获取到，抽奖所需f分，请联系管理员配置");
        }

        RaffleGoodsVO result = new RaffleGoodsVO();
        result.setPrizeGoodsList(prizeGoodsList);
//        result.setCurrentBalance();
        result.setPrice(dictionary.getValueName());
        return ResultUtil.data(result);
    }

    private LambdaQueryWrapper<PrizeGoods> createWrapper() {
        LambdaQueryWrapper<PrizeGoods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PrizeGoods::getPublishType, DictConstant.PUBLISH_TYPE_01);
        lambdaQueryWrapper.orderByDesc(PrizeGoods::getSortNo);
        lambdaQueryWrapper.orderByDesc(PrizeGoods::getGoodsPrice);
        return lambdaQueryWrapper;
    }

    /**
     * 获取当前剩余多少f分
     * @return 获取当前剩余多少f分
     */
    @Override
    public ResultMessage<Object> currentBalance() {
        AuthUser currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            throw new ServiceException("登陆已过期，请重新登陆后重试");
        }
        //获取当前用户的f分余额
        UserRes userMoney = payApi.getUserMoney(currentUser.getOpenId());
        return ResultUtil.data(String.valueOf(CurrencyUtil.div(new BigDecimal(userMoney.getBalance()).doubleValue(), 100)));
    }

    /**
     * 奖品规则列表
     *
     * @param dto
     * @return
     */
    @Override
    public Page<PrizeGoods> lotteryGoodsList(PrizeGoodsDTO dto) {
        Page<PrizeGoods> page = baseMapper.selectPage(new Page<>(dto.getPageNumber(), dto.getPageSize()), dto.toQueryWrapper());
        return this.conversion(page);
    }

    private Page<PrizeGoods> conversion(Page<PrizeGoods> page) {
        if (CollectionUtil.isEmpty(page.getRecords())) {
            return page;
        }
        List<Dictionary> goodsTypeList = dictionaryClient.getListByCode(DictConstant.GOODS_TYPE_NO);
        List<Dictionary> virtualTypeList = dictionaryClient.getListByCode(DictConstant.VIRTUAL_TYPE_NO);
        List<Dictionary> isNeedToCollectList = dictionaryClient.getListByCode(DictConstant.IS_NEED_TO_COLLECT_NO);
        List<Dictionary> publishTypeList = dictionaryClient.getListByCode(DictConstant.PUBLISH_TYPE_NO);
        for (PrizeGoods prizeGoods : page.getRecords()) {
            for (Dictionary dictionary : goodsTypeList) {
                if (dictionary.getValue().equals(String.valueOf(prizeGoods.getGoodsType()))) {
                    prizeGoods.setGoodsTypeName(dictionary.getValueName());
                }
            }
            for (Dictionary dictionary : virtualTypeList) {
                if (dictionary.getValue().equals(String.valueOf(prizeGoods.getVirtualType()))) {
                    prizeGoods.setVirtualTypeName(dictionary.getValueName());
                }
            }
            for (Dictionary dictionary : isNeedToCollectList) {
                if (dictionary.getValue().equals(String.valueOf(prizeGoods.getIsNeedToCollect()))) {
                    prizeGoods.setIsNeedToCollectName(dictionary.getValueName());
                }
            }
            for (Dictionary dictionary : publishTypeList) {
                if (dictionary.getValue().equals(String.valueOf(prizeGoods.getPublishType()))) {
                    prizeGoods.setPublishTypeName(dictionary.getValueName());
                }
            }
        }
        return page;
    }

    /**
     * 创建奖品规则
     *
     * @param prize
     * @return
     */
    @Override
    public ResultMessage<Object> createPrizeGoods(PrizeGoods prize) {
        if (DictConstant.GOODS_TYPE_02.equals(prize.getGoodsType()) && prize.getVirtualType() == null) {
            throw new ServiceException("是虚拟商品，但未选择虚拟商品种类");
        }
        if (baseMapper.insert(prize) > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }

    /**
     * 发布奖品
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Object> publishPrizeGoods(PrizeGoodsDTO dto) {
        LambdaUpdateWrapper<PrizeGoods> update = new LambdaUpdateWrapper<>();
        update.eq(PrizeGoods::getId, dto.getId());
        update.set(PrizeGoods::getPublishType, dto.getPublishType());
        return super.update(update) ? ResultUtil.success() : ResultUtil.error();
    }

    /**
     * 更新奖品规则
     *
     * @param prize
     * @return
     */
    @Override
    public ResultMessage<Object> updatePrizeConfig(PrizeGoods prize) {
        if (baseMapper.updateById(prize) > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }

    /**
     * 删除奖品规则
     *
     * @param id
     * @return
     */
    @Override
    public ResultMessage<Object> deletePrizeConfig(String id) {
        if (baseMapper.deleteById(id) > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }
}
